<script setup>
//region import
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";
import {getAllOrdersService, mealsOptionService} from "@/api/hospital";
import request from '@/utils/axiosUtils.js'
import router from '@/router/index.js'
import {ElMessage} from "element-plus";
import {getChatList, getChatUser} from "@/api/chat.js";
import {user} from "@/stores/counter.js";
//endregion
//region chat
const chats = ref([])
const users = ref([])
const client = ref(null);
const curUser = user()
getChatUser().then((res) => {
  users.value = res.data
})
onBeforeUnmount(() => {
  if (client.value) {
    client.value.close()
  }
})
function fetchData(){
  ElMessage.warning('正在拉取');
  getChatUser().then((res)=>{
    users.value=res.data;
    ElMessage.warning('拉取聊天记录成功')
  })
}
//endregion

const isloadingtable = ref(true)

const queryParams = ref({
  tabType: 0

})
// 用户提问
const questions = reactive([])
// AI回答
const answers = reactive(["你好，我是AI医疗小助手，请问有什么可以帮助你的吗？"])

const input = ref('');
const isLoading = ref(false)
const isshowlist = ref(true)
const isshowdetail = ref(false)
const handleSubmit = () => {
  if (isLoading === true) {
    ElMessage.error("请勿重复提问...")
    return;
  }
  isLoading.value = true
  if (client.value) {
    if(input.value.trim().length === 0){
      ElMessage.error("请输入内容")
      isLoading.value = false
    }else {
      client.value.send(input.value)
      isLoading.value = false
      chats.value.push({
        type: 2,
        content: input.value
      })
    }
  }
  input.value = ""
}

const drawer = ref(false)
var tableData = reactive([]);
const rawData = ref([
  {
    "orderid": "",
    "orderdate": "",
    "phone": "",
    "user": {
      "userid": "",
      "sysUserId": "",
      "realname": "",
      "sex": "",
      "identitycard": "",
      "birthday": ""
    },
    "hospital": {
      "hpId": "",
      "name": "",
      "picture": "",
      "telephone": "",
      "address": "",
      "businessHours": "",
      "deadline": "",
      "rule": "",
      "state": null
    },
    "setmeal": {
      "smid": "",
      "name": "",
      "type": "",
      "price": null
    },
    "state": null
  }
]);

//
const orderStates = reactive([
  {code: 0, name: "已取消", flag: false},
  {code: 1, name: "已下单", flag: false},
  {code: 2, name: "已付款", flag: false},
  {code: 3, name: "编辑", flag: true},
  {code: 4, name: "已归档", flag: true},
  {code: 5, name: "已过期", flag: false},
  {code: 6, name: "已退款", flag: false},
])

// 表单数据
const form = ref({
  phone: "",
  realName: "",
  sex: "",
  smid: "",
  orderdate: "",
  state: "",
  page: 1,
  size: "10"
});

const chatlist = ref([
  {
    pic: "@/assets/img/qiqi.png",
    name: 'user1'
  },
  {
    pic: '../assets/img/qiqi2.png',
    name: 'user2'
  },
  {
    pic: '../assets/img/qiqi.png',
    name: 'user3'
  },
  {
    pic: '../assets/img/qiqi2.png',
    name: 'user4'
  }
])

// 套餐选项
const options = ref([
  {
    value: "男士-基础套餐",
    label: "男士-基础套餐",
  },
]);

// 分页数据
const pagination = ref({
  currentPage: 1, // 当前页码
  pageSize: 10, // 每页显示条目个数
  total: 1, // 总条目数
});

const getOrdersByPage = async (currentPage) => {
  isloadingtable.value = true
  form.value.page = currentPage;
  await getAllOrdersService(form.value).then((res) => {
    console.log("获取到的数据是：", res);
    isloadingtable.value = false;
    if (res.code == 200) {
      rawData.value = res.data.data;
      getText();
      pagination.value.total = res.data.total;
      pagination.value.currentPage = currentPage;

    }
    console.log(pagination);
  });
}

const jumpToDetail = (row) => {
  router.push({
    path: '/detail',
    query: {
      orderid: row.id,
      phone: row.phoneNumber,
      realName: row.name,
      sex: row.sex,
      type: row.type,
      orderdate: row.date,
      state: row.state,
    },
  });
}

const getText = () => {
  tableData.splice(0, tableData.length);
  for (let i = 0; i < rawData.value.length; i++) {
    let sex = rawData.value[i].user.sex == 1 ? '男' : '女';
    tableData.push({
      id: rawData.value[i].orderid,
      phoneNumber: rawData.value[i].phone,
      name: rawData.value[i].user.realname,
      sex: sex,
      type: rawData.value[i].setmeal.name,
      hospital: rawData.value[i].hospital.name,
      date: new Date(rawData.value[i].orderdate).toLocaleDateString(),
      state: rawData.value[i].state,
    })
  }
}

const clearForm = async () => {
  form.value.phone = "",
      form.value.realName = "",
      form.value.sex = "",
      form.value.smid = "",
      //orderdate:"2024-07-08",
      form.value.orderdate = "",
      form.value.state = "",
      form.value.page = 1,
      form.value.size = "10",
      await getOrdersByPage(1);
};

const clearCache = async () => {
  request({
    url: '/orders/clear',
    method:'GET'
  }).then((res) => {
    ElMessage.warning(res.message);
  })
  location.reload();
}

onMounted(async () => {
  await mealsOptionService().then((res) => {
    if (res.code == 200) {
      options.value = res.data.map((item) => ({
        value: item.smid,
        label: item.name,
      }));
    }
  });
  await getOrdersByPage(1);
  //fetchData(1, 10);

});

const gochat = (userId) => {
  isshowlist.value = false
  isshowdetail.value = true
  getChatList(userId).then((res) => {
    chats.value = res.data
  })
  client.value = new WebSocket(`ws://localhost:7070/websocket/api1/${userId}/${curUser.userId}`);
  client.value.onopen = () => {
    console.log("连接成功")
  }
  client.value.onmessage = (msg) => {
    console.log(msg)
    chats.value.push(JSON.parse(msg.data))
  }
  client.onclose = () => {
    console.log("连接关闭")
  }
};


// 删除结论
const chatopen = () => {
  drawer.value = true;
};
//endregion
</script>

<template>
  <div class="wrapper">
    <el-container>
      <!-- 头部 -->
      <el-header class="hop-header">
        <el-page-header :icon="ArrowLeft" @click="router.push('/login')">
          <template #title>
            <span style="font-size: larger"> 返回 </span>
          </template>
          <template #content>
            <div
                style="display: flex;flex-direction: row;align-items: center;text-align: center;justify-content: center;">
              <img src="../assets/img/qiqi2.png"
                   style="width: 30px;margin: 0 5px;padding-top: 5px"/>
              <span style="font-size: larger"> 不卜庐养生堂体检报告管理系统 </span>
            </div>
          </template>
        </el-page-header>
        <div style="display: flex;flex-direction: row; align-items: center;margin-right: 60px">
          <div style="color: #333F29; font-weight: normal; font-size: medium;margin: 0 10px 4px;">
            医生：{{ curUser.realName }}
          </div>
          <el-divider direction="vertical"/>
          <el-button text @click="chatopen()">在线问诊</el-button>
          <el-divider direction="vertical"/>
          <el-button text @click="curUser.logout().then(()=>{ElMessage.success('登出成功');router.push('/login')})">
            退出登录
          </el-button>
        </div>
      </el-header>
      <el-container>
        <!-- 侧边栏 -->
        <el-aside class="hop-aside">
          <el-form :model="form" label-width="auto" class="aside-form">
            <div style="font-weight: bold; color: #171717; padding: 20px">
              体检用户查询
            </div>
            <el-form-item label="手机号码">
              <el-input v-model="form.phone" placeholder="手机号码" clearable/>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="form.realName" placeholder="姓名" clearable/>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="form.sex">
                <div style="display: flex; flex-direction: column">
                  <el-radio value="1" size="large" border>男</el-radio>
                  <el-radio value="0" size="large" border>女</el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="套餐类型">
              <el-select
                  v-model="form.smid"
                  placeholder="套餐类型"
                  size="default"
                  clearable>
                <el-option
                    v-for="item in options"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="体检日期">
              <el-date-picker
                  clearable
                  v-model="form.orderdate"
                  type="date"
                  placeholder="体检日期"
              />
            </el-form-item>
            <el-form-item label="是否归档">
              <el-radio-group v-model="form.state">
                <div style="display: flex; flex-direction: column">
                  <el-radio value="4" size="large" border>已归档</el-radio>
                  <el-radio value="3" size="large" border>未归档</el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="padding-left: 40px">
              <el-button type="primary" @click="getOrdersByPage(1)">查询</el-button>
              <el-button type="warning" @click="clearForm">重置</el-button>
              <el-button type="danger" @click="clearCache">刷新</el-button>
            </el-form-item>
          </el-form>
        </el-aside>
        <!-- 内容 -->
        <el-main class="hop-main">
          <el-tabs v-model="queryParams.tabType" @tab-click="handleTabClick" style="margin-left: 15px">
          </el-tabs>
          <!-- 表格 -->
          <el-table
              v-loading="isloadingtable"
              :data="tableData"
              style="width: 100%;height: 80%"
          >

            <el-table-column prop="id" label="预约编号" sortable/>
            <el-table-column prop="phoneNumber" label="手机号码" sortable/>
            <el-table-column prop="name" label="真实姓名" sortable/>
            <el-table-column prop="sex" label="性别" sortable>
              <template #default="scope">
                <el-tag size="large" type="danger" v-if="scope.row.sex==='女'">女</el-tag>
                <el-tag size="large" type="primary" v-else>男</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="体检套餐类型" sortable min-width="85px"/>
            <el-table-column prop="hospital" label="体检医院" sortable/>
            <el-table-column prop="date" label="体检日期" sortable/>
            <el-table-column label="操作" sortable>
              <template #default="scope">
                <div v-for="(item, index) in orderStates">
                  <el-button
                      type="text"
                      :disabled="!item.flag"
                      :style="{ color: !item.flag ? 'rgba(204,204,204,0.85)' : null }"
                      v-if="scope.row.state === item.code"
                      @click="jumpToDetail(scope.row)"
                  >
                    {{ item.name }}
                  </el-button>
                </div>

              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <div style="display: flex;flex-direction: row;justify-content: flex-end;align-items: center">
            <el-pagination
                background
                style="padding-top: 20px"
                layout="prev, pager, next,total"
                :default-current-page="pagination.currentPage"
                :total="pagination.total"
                :page-size="pagination.pageSize"
                @change="
              (currentPage) => {
                getOrdersByPage(currentPage);
              }">
            </el-pagination>
          </div>

          <!--聊天抽屉-->
          <el-drawer
              v-model="drawer"
              title="聊天列表"
              :direction="direction"
              :before-close="handleClose"
          >
            <!--聊天用户卡片-->
            <el-button
                text
                v-show="!isshowdetail"
                size="small"
                @click="fetchData">
              刷新
            </el-button>
            <div v-for="(item, index) in users" :key="index"
                 style="display: flex; flex-direction: column; align-items: center;" v-show="isshowlist">
              <el-card
                  @click="gochat(item.sysUserId)"
                  class="chat-card"
                  shadow="always">
                <div style="display: flex; align-items: center;">
                  <img src="../assets/img/qiqi2.png"
                       style="width: 50px; height: 50px; border-radius: 25px; margin-right: 10px;"/>
                  <span>{{ item.realname }}</span>
                  <el-button style="margin-left: auto;" @click.stop="gochat(item.sysUserId)">进入聊天</el-button>
                </div>
              </el-card>

            </div>

            <!--聊天页面-->
            <div v-show="isshowdetail">
              <el-page-header @back="goBack" @click="isshowdetail=false;isshowlist=true;">
                <template #title><span style="font-size: x-small;color: gray">返回</span></template>
              </el-page-header>
              <div class="chat-area">
                <div align="center">
                  <div class="tip">
                    本平台仅提供医患沟通交流平台，医生在平台上进行的回复、建议等内容，均需谨慎规范，并需明确告知患者，
                    平台提供的咨询内容仅供参考，不作为诊断和治疗的依据。医生需指导患者及时就医，本平台不对医生的回复内容承担任何责任。
                  </div>
                </div>
                <div v-for="(item,index) in chats" :key="index">
                  <div class="ai-message-item" v-if="item.type==1">
                    <div class="ai-message">
                      {{ item.content }}
                    </div>
                  </div>
                  <div class="user-message-item" v-else>
                    <div class="user-message">
                      {{ item.content }}
                    </div>
                  </div>
                </div>
                <div style="height: 10vh;background-color: transparent"/>
              </div>
              <!--输入区域-->
              <div class="input-box" v-show="isshowdetail" style="margin-bottom:20px">
                <el-input placeholder="请输入对话内容"
                          @keyup.enter="handleSubmit"
                          v-model="input"
                          clearable size="large" style="padding: 2vh 1vw 2vh 1vw;">
                  <template #append>
                    <el-button @click="handleSubmit" v-loading="isLoading">
                      <template #icon>
                        <i class="fa fa-send"></i>
                      </template>
                    </el-button>
                  </template>
                </el-input>
              </div>
            </div>


          </el-drawer>


        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>

.hop-header {
  background-color: #F7F7F7;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  height: 8vh;
}

.hop-aside {
  background-color: #F7F7F7;
}

.hop-main {
  background-color: #F7F7F7;
  display: flex;
  flex-direction: column;

  height: 100vh;
  width: 100vw;
  padding-top: 0px;
}

.aside-form {
  background-color: #FFFFFF;
  border-radius: 2%;
  box-shadow: 2px 2px 5px rgba(204, 204, 204, 0.5);
  font-family: "Microsoft YaHei";
  margin: 11px 5px 5px 10px;
  font-size: larger;
  max-width: 600px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.aside-form > * {
  width: 250px;
}

.aside-form :deep(.el-form-item__label) {
  color: #171717;
}

.aside-form .el-radio {
  color: #171717;
  border-color: #FFFFFF;
}

.el-button--primary {
  background-color: #07C160;
  color: #FFFFFF;
  border: transparent;
}

.el-button--warning {
  background-color: #FFC300;
  color: #FFFFFF;
  border: transparent;
}

.el-button--danger {
  background-color: #FA5151;
  color: #FFFFFF;
  border: transparent;
}

.hop-main :deep(.el-pagination.is-background .el-pager li.is-active) {
  background-color: #ACACAC;
}

.hop-main :deep(.el-button--text) {
  color: #576B95;
}

.hop-main :deep(.el-table thead) {
  color: rgba(63, 63, 63, 0.7);
  font-weight: lighter;
}

.hop-main :deep(.el-table) {
  color: #1E1E1E;
  font-weight: normal;
}

.input-box {
  padding-bottom: 2vh;
  width: 100%;
  height: 4vw;
  position: absolute;
  bottom: -3vh;
  left: 0;
  background-color: #f2f2f2;
}


.tip {
  width: 25vw;
  font-size: xx-small;
  background-color: #c5c5c5;
  color: #FFFFFF;
  padding: 1vw;
}

.ai-message {
  background-color: #FFFFFF;
  font-size: 2.25vh;
  box-shadow: 0 0 1vh 0 rgba(0, 0, 0, 0.2);
  margin: 2vh 5vw 2vh 0vw;
  padding: 1.25vh;
  border-radius: 5%;
}

.ai-message-item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: stretch
}

.user-message {
  background-color: #3D96F2;
  color: #FFFFFF;
  font-size: 2.25vh;
  box-shadow: 0 0 1vh 0 rgba(0, 0, 0, 0.2);
  margin: 2vh 0vw 2vh 5vw;
  padding: 1.25vh;
  border-radius: 5%;
}

.user-message-item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-end;
  align-items: flex-start;
  align-content: stretch
}

.myicon {
  scale: 200%;
}

.chat-card {
  width: 480px;
  margin-bottom: 10px;
  scale: 75%;
  transition: transform 0.3s ease; /* 添加过渡效果，使其平滑变化 */
}

.chat-card:hover {
  transform: scale(1.075); /* 鼠标悬停时放大 10% */
  cursor: pointer; /* 可选：改变鼠标指针样式 */
}

</style>